<template>
  <div class="payApprove">
    <!-- search part-->
    <div class="btns" style="padding:1em 0;margin-bottom:1em;background:#fff;position:relative;">
      <div style="margin-left: 1em">
        <el-select v-model="searchForm.condition" placeholder="请选择业务范围" @change="conditionChange">
          <el-option-group label="个人业务">
            <el-option key="1" label="未完成(Person)" value="1"></el-option>
            <el-option key="2" label="已完成(Person)" value="2"></el-option>
          </el-option-group>
          <el-option-group label="全部业务">
            <el-option key="3" label="未完成(ALL)" value="3"></el-option>
            <el-option key="4" label="已完成(ALL)" value="4"></el-option>
          </el-option-group>
        </el-select>
        <el-select v-model="searchForm.projectId" @change="proSelectChange" placeholder="选择项目" filterable clearable>
          <el-option v-for="item in options.projects" :keys="item.id" :label="item.projectName" :value="item.id" />
        </el-select>
        <el-select v-model="searchForm.otherId" placeholder="选择合同" filterable clearable>
          <el-option v-for="item in options.contracts" :keys="item.id" :label="item.contractNo" :value="item.id"/>
        </el-select>
        <el-date-picker
          style="margin-left: 8px"
          v-model="searchForm.time"
          unlink-panels
          value-format="timestamp"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-button @click="toSearch" type="primary" icon="el-icon-search" size="small" style="margin: 4px 0 0 6px" >查询</el-button>
      </div>
    </div>
    <!-- modify and detail part-->
    <div class="modifyPart">
      <div>
        <el-button type="primary" :disabled="searchForm.otherId?false:true" icon="el-icon-plus" size="small" @click="addAuditRecord">新增</el-button>
        <el-button v-if="table.selected.length === 1" type="warning" icon="el-icon-edit" size="small" @click.native.stop="updateAuditRecord()">修改</el-button>
        <el-button v-if="table.selected.length > 0" type="danger" icon="el-icon-delete" size="small" @click.native.stop="deleteAuditRecord()">删除</el-button>
        <el-button v-if="table.selected.length === 1" size="small" @click="print()"><a-icon type="printer"/>打印</el-button>
        <a-table
          bordered
          class="tableStyle"
          :loading="table.loading"
          :pagination="table.pagination"
          size="middle"
          :data-source="table.data"
          :rowKey="record => record.id"
          :customRow="rowClick"
          :row-selection="{ selectedRowKeys: table.selected, onChange: onSelectChange }">
          <a-table-column align="center" key="purContract" title="采购合同" data-index="purContract" ellipsis="true"/>
          <a-table-column align="center" key="supplier" title="收款单位" data-index="supplier" ellipsis="true"/>
          <a-table-column align="center" key="price" title="付款金额(￥)" data-index="price" ellipsis="true"/>
          <a-table-column align="center" key="account" title="收款账户" data-index="account" ellipsis="true"/>
          <a-table-column align="center" key="bankOfDeposit" title="开户银行" data-index="bankOfDeposit" ellipsis="true"/>
          <a-table-column align="center" key="matter" title="付款事由" data-index="matter" ellipsis="true"/>
          <a-table-column align="center" key="method" title="付款方式" data-index="method" ellipsis="true"/>
          <a-table-column align="center" key="unapproved" title="审核状态" data-index="unapproved">
            <template slot-scope="t, r">
              <a-badge v-if="t == 0" status="success" text="审核完成" />
              <a-badge v-else status="default" text="审核中" />
            </template>
          </a-table-column>
          <a-table-column align="center" key="createBy" title="申请人" data-index="createBy" ellipsis="true"/>
          <a-table-column align="center" key="createTime" title="申请时间" data-index="createTime" ellipsis="true">
            <template slot-scope="text, record">
              {{dateFormat(text)}}
            </template>
          </a-table-column>
          <a-table-column
            key="operation"
            title="操作"
            data-index="operation"
            align="center"
            :width="230">
            <template slot-scope="text, record, index">
              <a-button type="link" size="small" @click.native.stop="findReviewProgress(record.id)">申请进度</a-button>
            </template>
          </a-table-column>
        </a-table>
      </div>
    </div>


    <!--审批进度模态框-->
    <el-dialog v-el-drag-dialog title="审批进度" :visible.sync="reviewProgress.visible">
      <a-table
        bordered
        style="margin-top: 1em"
        :loading="reviewProgress.loading"
        size="middle"
        :data-source="reviewProgress.data"
      >
        <a-table-column align="center" key="checkSort" title="审批序号" data-index="checkSort"/>
        <a-table-column align="center" key="reviewer" title="审批人" data-index="reviewer"/>
        <a-table-column align="center" key="auditStatus" title="审批状态" data-index="auditStatus">
          <template slot-scope="text, record">
            <span v-if="text == 0" type="info">{{'未审核'}}</span>
            <span v-else-if="text == 1" type="success">{{'通过'}}</span>
            <span v-else-if="text == 2" type="danger">{{'否决'}}</span>
          </template>
        </a-table-column>
        <a-table-column align="center" key="reviewComments" title="批注" data-index="reviewComments"/>
        <a-table-column align="center" key="auditTime" title="审批时间" data-index="auditTime">
          <template slot-scope="text, record">
            {{dateFormat(text)}}
          </template>
        </a-table-column>
      </a-table>
    </el-dialog>

    <!--新增审批内容-->
    <el-dialog v-el-drag-dialog title="发起资金使用审批" :visible.sync="addApprove.visible" @close="addApproveClose">
      <el-form  ref="addApprove.form" :rules="addApprove.codeRules" :model="addApprove.form"  status-icon>
        <a-row type="flex" justify="center">
          <a-col :span="20">
            <a-row type="flex" justify="space-between">
              <a-col :span="10">
                <el-form-item label="收款单位" label-width="80px" size="small" prop="payeeId">
                  <el-select v-model="addApprove.form.payeeId" filterable clearable @change="supplyChange">
                    <el-option v-for="item in addApprove.supplyData" :key="item.id" :value="item.id" :label="item.supplier"></el-option>
                  </el-select>
                </el-form-item>
              </a-col>
              <a-col :span="10">
                <el-form-item label="付款金额" label-width="80px" size="small" prop="price">
                  <el-input type="text" v-model="addApprove.form.price"></el-input>
                </el-form-item>
              </a-col>
            </a-row>
            <a-row type="flex" justify="space-between">
              <a-col :span="10">
                <el-form-item label="开户银行" label-width="80px" size="small" prop="bankOfDeposit">
                  <el-select v-model="addApprove.form.bankOfDeposit" filterable clearable @change="bankChange">
                    <el-option v-for="item in addApprove.bankData" :key="item.id" :value="item.id" :label="item.bankOfDeposit"></el-option>
                  </el-select>
                </el-form-item>
              </a-col>
              <a-col :span="10">
                <el-form-item label="收款账户" label-width="80px" size="small" prop="account">
                  <el-input type="text" v-model="addApprove.form.account" disabled="disabled"></el-input>
                </el-form-item>
              </a-col>
            </a-row>
            <a-row type="flex" justify="space-between">
              <a-col :span="10">
                <el-form-item label="付款事由" label-width="80px" size="small" prop="matter">
                  <el-input type="text" v-model="addApprove.form.matter"></el-input>
                </el-form-item>
              </a-col>
              <a-col :span="10">
                <el-form-item label="付款方式" label-width="80px" size="small" prop="method">
                  <el-input type="text" v-model="addApprove.form.method"></el-input>
                </el-form-item>
              </a-col>
            </a-row>
            <a-row type="flex" justify="space-between">
              <a-col :span="10">
                <el-form-item label="备注" label-width="80px" size="small" prop="remark">
                  <el-input type="text" v-model="addApprove.form.remark"></el-input>
                </el-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :span="20">
            <a-row type="flex" justify="start" v-for="(data,index) in addApprove.form.dataList">
              <a-col :span="10">
                <el-form-item label="审核人" label-width="80px" size="small" prop="reviewer">
                  <el-select v-model="data.reviewer" filterable clearable>
                    <el-option v-for="item in addApprove.userData" :key="item.id" :value="item.id" :label="item.username"></el-option>
                  </el-select>
                </el-form-item>
              </a-col>
              <a-col :span="10">
                <el-form-item>
                  <a-button type="danger" ghost @click="delRowCustom(index)" icon="minus"></a-button>
                </el-form-item>
              </a-col>
            </a-row>
            <a-button @click="addRowCustom" style="width: 98%;border-style: dashed" icon="plus">新增</a-button>
          </a-col>
        </a-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="addApprove.visible = false">取 消</el-button>
        <el-button type="primary" size="small" :loading="addApprove.subLoading" @click="submitHandler('addApprove.form')">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import '@/styles/auto-style.css'
  import { getAction, postActionByJson, postActionByQueryString } from "@/api/manage";
  import { dateTimeFormat, dateFormat } from "@/utils/format";
  import elDragDialog from '@/directive/el-drag-dialog'

  export default {
    directives: { elDragDialog },
    created() {
      this.loadPurchaseProjects()
      this.loadContracts()
      this.searchForm.condition = '1'
      this.toSearch()
    },
    data() {
      return {
        addApprove: {
          //供应商下拉框
          supplyData: [],
          //审核人下拉框
          userData: [],
          //银行下拉框
          bankData: [],
          visible: false,
          form: {dataList: []},
          subLoading: false,
          codeRules: {
            payeeId: [
              {required: true, message: '不能为空', trigger: 'blur'}
            ],
            price: [
              {required: true, pattern: /^[1-9]\d*\,\d*|[1-9]\d*$/, message: '格式不正确', trigger: 'blur'}
            ]
          }
        },
        reviewProgress: {
          visible: false,
          data: [],
          loading: false
        },
        options: {
          projects: [],
          contracts: [],
        },
        searchForm: {},
        table: {
          data: [],
          loading: false,
          selected: [],
          pagination: {
            showTotal: total => `共 ${total} 条结果`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '50'],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            onChange: (pageNum) => {
              this.table.pagination.pageNum = pageNum
              this.toSearch()
            },
            onShowSizeChange: (pageNum, pageSize) => {
              this.table.pagination.pageSize = pageSize
              this.toSearch()
            } // 改变每页数量时更新显示
          },
        },
        dateFormat,
        url: {
          findPurchaseContractFundsApproval: '/examine/funds/findPurchaseContractFundsApproval',
          findAllLike: '/purchase/project/findAllLike',
          findByProjectId: '/purchase/contract/findByProjectId',
          findReviewProgress: '/examine/record/findReviewProgress',
          findAll: '/user/findAll',
          findSupplierByParams: '/supply/supplier/findSupplierByParams',
          findSupplierBank: '/supply/supplier/findSupplierBank',
          findSupplierBankAccount: '/supply/supplier/findSupplierBankAccount',
          findBankAccount: '/supply/supplier/findBankAccount',
          saveOrUpdateFundsApproval: '/examine/funds/saveOrUpdateFundsApproval',
          findFundsApproval: '/examine/funds/findFundsApproval',
          deleteFundsApproval: '/examine/funds/deleteFundsApproval'
        }
      }
    },
    methods: {
      print(){
        if (this.table.selected.length === 1) {
          let id = this.table.selected[0]
          window.open(`http://172.16.4.238:14012/xzx/jmreport/view/607420648900612096?fundsId=${id}`)
        }
      },
      conditionChange(){
        if (this.searchForm.condition){
          this.$delete(this.searchForm, 'proDetailId')
          this.loadPurchaseProjects()
        }
      },
      rowClick(row, index){
        return {
          on: {
            click: ()=>{
              let rowKeys = this.table.selected;
              if (rowKeys.length > 0 && rowKeys.includes(row.id)) {
                rowKeys.splice(rowKeys.indexOf(row.id), 1);
              } else {
                rowKeys.push(row.id);
              }
              this.table.selected = rowKeys;
            }
          }
        }
      },
      addApproveClose(){
        //关闭模态框后初始化数据
        this.addApprove.form = {}
        this.addApprove.form.dataList = []
        this.addApprove.form = {...this.addApprove.form}
      },
      bankChange(){
        if (this.addApprove.form.bankOfDeposit){
          getAction(this.url.findBankAccount, { bankId: this.addApprove.form.bankOfDeposit})
          .then(resp =>{
            this.addApprove.form.account = resp.data.account
            this.addApprove.form = {...this.addApprove.form}
          })
        }
      },
      supplyChange(){
        if (this.addApprove.form.payeeId){
          getAction(this.url.findSupplierBank, { supplierId: this.addApprove.form.payeeId})
          .then(resp =>{
            this.addApprove.bankData = resp.data
          })
        }
      },
      addRowCustom() {
        this.addApprove.form.dataList.push({})
      },
      delRowCustom(index) {
        this.addApprove.form.dataList.splice(index, 1)
      },
      deleteAuditRecord(){
        this.$confirm('是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.table.selected.length > 0){
            postActionByQueryString(this.url.deleteFundsApproval, {ids: this.table.selected})
              .then(resp =>{
                this.$message.success(resp.message + '条删除成功')
              }).catch(()=>{
              this.$message.error('删除失败')
            }).finally(()=>{
              this.toSearch()
            })
          }else {
            this.$message({ type: 'warning', message: '请选择要删除的行'})
          }
        })
      },
      updateAuditRecord(){
        if (this.table.selected.length === 1){
          getAction(this.url.findFundsApproval, {fundsId: this.table.selected[0]})
          .then(resp =>{
            this.addApprove.form = {}
            this.addApprove.form = resp.data.examineFunds
            this.addApprove.form.dataList = resp.data.records
            this.addApprove.form = {...this.addApprove.form}
            this.loadReviewer()
            this.loadSupply()
            this.supplyChange()
            this.addApprove.visible = true
          }).catch(()=>{
            this.$message.error('点击失败')
          })
        }else {
          this.$message({ type: 'warning', message: '请选一个需要修改的项'})
        }
      },
      submitHandler(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            let approve = {}
            let arr = []
            this.addApprove.form.dataList.forEach(function(item, index) {
              let obj = {}
              obj.reviewer = item.reviewer
              obj.checkSort = index + 1
              arr.push(obj)
            })
            //补充审批内容
            approve.examineFunds = this.addApprove.form
            //移除dataList
            this.$delete(approve.examineFunds, 'dataList')
            //绑定合同
            approve.examineFunds.otherId = this.searchForm.otherId
            approve.records = arr
            if(arr.length === 0){
             this.$message({ type: 'warning', message: '请添审核人'})
             return
            }
            postActionByJson(this.url.saveOrUpdateFundsApproval, approve)
            .then(resp =>{
              this.$message.success(resp.message + '条提交成功')
            }).catch((e)=>{
              this.$message.error('提交失败')
            }).finally(()=>{
              this.addApprove.visible = false
              this.toSearch()
            })
          }
        })
      },
      findReviewData(id){
        this.reviewProgress.data = []
        this.reviewProgress.loading = true
        getAction(this.url.findReviewProgress, {fundsId: id})
        .then(resp =>{
          if (resp.data){
            this.reviewProgress.data = resp.data
          }
        }).catch(()=>{
          this.$message.error('审批进度查询失败')
        }).finally(()=>{
          this.reviewProgress.loading = false
        })
      },
      findReviewProgress(id){
        this.reviewProgress.visible = true
        this.findReviewData(id);
      },
      onSelectChange(ids, rows){
        this.table.selected = []
        const itemsId = []
        rows.map(item => {
          itemsId.push(item.id)
        })
        this.table.selected = itemsId
      },
      addAuditRecord(){
        this.loadReviewer()
        this.loadSupply()
        this.addApprove.visible = true
      },
      toSearch() {
        this.table.loading = true
        this.table.selected = []
        let obj = {}
        obj.pageNo = this.table.pagination.pageNum
        obj.pageSize = this.table.pagination.pageSize
        obj.condition = this.searchForm.condition
        obj.contractId = this.searchForm.contractId
        if (this.searchForm.time && this.searchForm.time.length > 0){
          obj.startTime = this.searchForm.time[0]
          obj.endTime = this.searchForm.time[1]
        }
        getAction(this.url.findPurchaseContractFundsApproval, obj)
        .then(resp=>{
          if (resp.data){
            this.table.data = resp.data.records
            this.table.pagination.pageNum = resp.data.current
            this.table.pagination.pageSize = resp.data.size
            this.table.pagination.total = resp.data.total
          }
        }).catch(()=>{
          this.$message.error('查询失败')
        }).finally(()=>{
          this.table.loading = false
        })
      },
      proSelectChange() {
        this.searchForm.otherId = ''
        this.loadContracts()
      },
      /**
       * 加载下拉框所有采购项目
       */
      loadPurchaseProjects() {
        getAction(this.url.findAllLike)
        .then((resp) => {
          this.options.projects = resp.data
        })
      },
      // 查询合同列表
      loadContracts() {
        getAction(this.url.findByProjectId, { projectId: this.searchForm.projectId })
        .then(resp => {
          this.options.contracts = resp.data
        })
      },
      loadReviewer(){
        getAction(this.url.findAll)
        .then(resp =>{
          this.addApprove.userData = resp.data
        }).catch(()=>{
          this.$message.error('审核人预加载失败')
        })
      },
      loadSupply(){
        getAction(this.url.findSupplierByParams)
        .then(resp =>{
          this.addApprove.supplyData = resp.data
        })
      }
    },
  };
</script>
<style lang="scss"  scoped>
  .modifyPart {
    background-color: white;
    margin-top: 15px;
    margin-bottom: 15px;
    padding: 15px;
  }
  .tableStyle{
    margin-top: 1em;
  }
</style>
